from flask import Blueprint, request, session, render_template, abort
from models.user import LoginLog, db
from utils.decorators import login_required, admin_required
from sqlalchemy import desc

log_bp = Blueprint('log', __name__, url_prefix='/logs')

@log_bp.route('/')
@login_required
@admin_required
def list_logs():
    """
    显示登录日志列表
    """
    # 获取分页参数
    page = request.args.get('page', 1, type=int)
    per_page = 20
    
    # 查询登录日志，按时间倒序排列
    logs_query = LoginLog.query.order_by(desc(LoginLog.login_time))
    
    # 分页
    logs = logs_query.paginate(
        page=page, 
        per_page=per_page, 
        error_out=False
    )
    
    return render_template('auth/logs.html', logs=logs)

@log_bp.route('/user/<int:user_id>')
@login_required
def user_logs(user_id):
    """
    显示特定用户的登录日志
    """
    # 检查权限：普通用户只能查看自己的日志，管理员可以查看所有用户的日志
    if session.get('user_id') != user_id and not (session.get('user_id') == 1 or session.get('username') == 'admin'):
        abort(403)
    
    # 获取分页参数
    page = request.args.get('page', 1, type=int)
    per_page = 20
    
    # 查询特定用户的登录日志，按时间倒序排列
    logs_query = LoginLog.query.filter_by(user_id=user_id).order_by(desc(LoginLog.login_time))
    
    # 分页
    logs = logs_query.paginate(
        page=page, 
        per_page=per_page, 
        error_out=False
    )
    
    return render_template('auth/logs.html', logs=logs)